import Toast from '../../../component/Toast';
import {routerRedux} from 'dva/router';
import {clone, trim, scrollTop} from '../../../util/utils';
import {getLoginSession, removeLoginSession} from '../../../plugin/loginSession';
import {removeWebState} from '../../../plugin/webLocalStore';
import {
	addBlog,
    removeBlog,
    pageBlogByUserId,
    addLabel,
    removeLabel,
    listLabelByUserId,
    addLabelLink,
    removeLabelLink,
    sortLabelByLabelIdList,
} from '../service/blogService';

const defaultState = {
	defaultUserId: '59080870585171968',
	blogPageInfo: undefined,
	labelList: [],
	labelModal: {
		visible: false,
		currentRecordId: undefined,
		labelName: '',
		selectedLabelIdMap: {},
	},
	filter: {
		labelIdMap: {},
	},
	// 每次进入博客中保存滚动距离
	scrollTopRecord: undefined
};

export default {

	namespace: 'home',
	
	state: {...defaultState},
	
	reducers: {
		
		resetState(state) {
			return {...defaultState, ...{inRecordId: state.inRecordId}};
		},
		
		changeBlogPageInfo(state, {payload}) {
			return {...state, ...{blogPageInfo: payload}};
		},
		
		changeLabelList(state, {payload}) {
			return {...state, ...{labelList: payload}};
		},
		
		changeLabelModalVisible(state, {payload, currentRecordId}) {
			let stateClone = clone(state);
			stateClone.labelModal.visible = payload;
			if(currentRecordId) {
				stateClone.labelModal.currentRecordId = currentRecordId;
				stateClone.labelModal.selectedLabelIdMap = [];
				let {list} = stateClone.blogPageInfo;
				for(let blog of list) {
					let {recordId, labelList} = blog;
					if(recordId == currentRecordId) {
						if(labelList) {
							for(let label of labelList) {
								stateClone.labelModal.selectedLabelIdMap[label.labelId] = true;
							}
						}
					}
				}
			}
			return stateClone;
		},
		
		changeLabelModalLabelName(state, {payload}) {
			let stateClone = clone(state);
			stateClone.labelModal.labelName = payload;
			return stateClone;
		},
		
		changeLabelModalSelectedLabelIdMap(state, {payload}) {
			let stateClone = clone(state);
			stateClone.labelModal.selectedLabelIdMap = payload;
			return stateClone;
		},
		
		changeFilterLabelIdMap(state, {payload}) {
			let stateClone = clone(state);
			stateClone.filter.labelIdMap = payload;
			return stateClone;
		},
		
		filter(state) {
			let stateClone = clone(state);
			let list = stateClone.blogPageInfo.list;
			let labelIdMap = stateClone.filter.labelIdMap;
			if(labelIdMap) {
				let hk = false;
				for(let key in labelIdMap) {
					hk = true;
					break;
				}
				// 过滤
				for(let blog of list) {
					let {labelList=[]} = blog;
					blog.hidden = hk;
					for(let label of labelList) {
						if(labelIdMap[label.labelId]) {
							blog.hidden = false;
							break;
						}
					}
				}
			}
			return stateClone;
		},
		
		setScrollTopRecord(state, {scrollTopRecord}) {
			return {...state, ...{scrollTopRecord}};
		}
		
	},
	
	effects: {
		
		*init(action, {put}) {
			let loginSession = yield getLoginSession();
			if(!loginSession) {
				// yield put({type: 'resetState'});
			}
			yield put({type: 'pageBlogByUserId'});
			yield put({type: 'listLabel'});
		},
		
		*logout(action, {put}) {
			removeLoginSession();
			removeWebState();
			yield put(routerRedux.push('/'));
		},
		
		*toEdit(action, {put}) {
			let res = yield addBlog('标题', '');
			if (res.code == 1) {
				yield put({type: 'setScrollTopRecord', scrollTopRecord: scrollTop()});
				yield put(routerRedux.push('/blogDetail/' + res.data.recordId));
				yield put({type: 'blogDetail/changeBlogEdit', payload: true});
				yield put({type: 'init'});
			} else 
				Toast.show(res.msg);
		},
		
		*toBlogDetail({payload: {blog}}, {put}) {
			yield put({type: 'setScrollTopRecord', scrollTopRecord: scrollTop()});
			yield put(routerRedux.push('/blogDetail/' + blog.recordId));
			yield put({type: 'blogDetail/changeBlogEdit', payload: false});
		},
		
		*removeBlog({payload}, {put}) {
			let res = yield removeBlog(payload);
			Toast.show(res.msg);
			yield put({type: 'init'});
		},
		
		*pageBlogByUserId(action, {put, select}) {
			let {defaultUserId} = yield select(state => state.home);
			let loginSession = yield getLoginSession();
			let userId = (loginSession && loginSession.user.userId) || defaultUserId;
			let res = yield pageBlogByUserId(userId, 'create_time desc', 1, 9999999);
			if(res.code == 1) {
				yield put({type: 'changeBlogPageInfo', payload: res.data});
				yield put({type: 'filter'});
			} else {
				Toast.show(res.msg)
			}
		},
		
		*listLabel(action, {put, select}) {
			let {defaultUserId} = yield select(state => state.home);
			let loginSession = yield getLoginSession();
			let userId = (loginSession && loginSession.user.userId) || defaultUserId;
			let res = yield listLabelByUserId(userId);
			if(res.code == 1) {
				yield put({type: 'changeLabelList', payload: res.data});
			} else {
				Toast.show(res.msg)
			}
		},
		
		*addLabel(action, {put, select}) {
			let {labelName} = yield select(state => state.home.labelModal);
			labelName = trim(labelName);
			if(labelName) {
				let res = yield addLabel(labelName);
				if(res.code != 1) {
					Toast.show(res.msg)
				}
				yield put({type: 'listLabel'});
			} else {
				Toast.show('请输入标签名称');
			}
			yield put({
				type: 'changeLabelModalLabelName',
        		payload: '',
       		});
		},
		
		*removeLabel({labelId}, {put, select}) {
			let res = yield removeLabel(labelId);
			if(res.code != 1) {
				return Toast.show(res.msg)
			}
			let labelIdMap = yield select(state => state.home.filter.labelIdMap);
			let labelIdMapClone = clone(labelIdMap);
			delete labelIdMapClone[labelId];
			yield put({
				type: 'changeFilterLabelIdMap',
        		payload: labelIdMapClone,
       		});
       		yield put({type: 'listLabel'});
		},
		
		*LabelLink({labelId, currentSelected}, {select, put}) {
			let {blogPageInfo: {list}, labelModal: {currentRecordId, selectedLabelIdMap}} = yield select(state => state.home);
			let selectedLabelIdMapClone = clone(selectedLabelIdMap);
			if(currentSelected) {
				delete selectedLabelIdMapClone[labelId];
			} else {
				selectedLabelIdMapClone[labelId] = true;
			}
			yield put({
				type: 'changeLabelModalSelectedLabelIdMap',
        		payload: selectedLabelIdMapClone,
       		});
       		// 延迟请求
       		let res;
       		if(currentSelected) {
       			res = yield removeLabelLink(currentRecordId, labelId);
       		} else {
       			res = yield addLabelLink(currentRecordId, labelId);
       		}
       		if(res.code != 1) {
       			Toast.show(res.msg);
       		}
		},
		
		*filterLabelIdMap({labelId, currentSelected}, {select, put}) {
			let labelIdMap = yield select(state => state.home.filter.labelIdMap);
			let labelIdMapClone = clone(labelIdMap);
			if(currentSelected) {
				delete labelIdMapClone[labelId];
			} else {
				labelIdMapClone[labelId] = true;
			}
			yield put({
				type: 'changeFilterLabelIdMap',
        		payload: labelIdMapClone,
       		});
			yield put({type: 'filter'});
		}
		
	},
	
	subscriptions: {
		
		reset({dispatch, history}) {
			history.listen(({ pathname }) => {
		        if (pathname === '/') {
		        	dispatch({type: 'init'});
		        }
			});
		}
		
	}
	
}